/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {DeviceEventEmitter, ListView, ScrollView, StyleSheet, Text, View} from 'react-native';

import Navigation from "../../../custom/Navigation";
import StyleUtils from "../../../res/styles/StyleUtils";
import ViewUtils from "../../../utils/ViewUtils";
import IparNetwork, {getSynPaysSellerAuth, SERVER_TYPE, SynpaysTeken} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import AddBackCardPage from "./AddBackCardPage";
import AlertDialog from "../../../custom/AlertDialog";


let ds;
let bankCard = [];
export default class BankCardPage extends Component<> {

    constructor(props) {
        super(props);
        bankCard = [];
        ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            showDialog: false,
            country: null,
            userId: '',
            dataSource: ds.cloneWithRows([]),
        };
        this.iparNetwork = new IparNetwork()
    }

    componentWillUnmount() {
        this.iparNetwork = null;
    }

    componentDidMount() {
        CommonUtils.showLoading();

        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                this.setState({
                    userId: JSON.parse(result).main_user_id,
                    country: JSON.parse(result).country,
                });
                // this.getDebitCardInfo();
                this.getCreditCardInfo();
            });


    }

    /*获取借记卡*/
    // getDebitCardInfo() {
    //     this.iparNetwork.getRequest(SERVER_TYPE.synPays + 'DebitCard?', 'Auth=' + getSynPaysSellerAuth(this.state.country, 1) + '&UserID=' + this.state.userId)
    //         .then((result) => {
    //             CommonUtils.dismissLoading();
    //
    //             if (result.ApiResponseCode === 200) {
    //                 for (i = 0; i < result.data.length; i++) {
    //                     bankCard.push(result.data[i]);
    //                 }
    //
    //                 this.setState({dataSource: ds.cloneWithRows(bankCard)})
    //             }
    //         })
    //         .catch((error) => {
    //             CommonUtils.dismissLoading();
    //
    //             console.log(error);
    //         });
    //
    //
    // }

    /*获取信用卡*/
    getCreditCardInfo() {
        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'getCardInfo?', 'UserID=' + this.state.userId + "&Type=CreditCard")
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    this.setState({dataSource: ds.cloneWithRows(result.data)})
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log(error);
            })
    }

    // /*删除借记卡*/
    // getDeleteDebitCard(cardId) {
    // 	let data = {
    // 		Auth: getSynPaysSellerAuth(this.state.country,1),
    // 		UserID: this.state.userId,
    // 		CardID: cardId,
    // 	};
    //
    // 	this.iparNetwork.getPostJson(SERVER_TYPE.synPays + 'Partner/RemoveDebitCard', data)
    // 		.then((result) => {
    //
    // 			if (result.ApiResponseCode === 200) {
    // 				bankCard = [];
    // 				//this.getDebitCardInfo();
    // 				this.getCreditCardInfo();
    // 				DeviceEventEmitter.emit('toast', I18n.t('default.success'))
    // 			}else {
    //                 CommonUtils.dismissLoading();
    //
    //             }
    // 		})
    // 		.catch((error) => {
    //             CommonUtils.dismissLoading();
    //
    //             console.log(error);
    // 		})
    //
    // }


    /*删除信用卡*/
    getDeleteCreditCard(cardId) {
        let data = {
            UserID: this.state.userId,
            CardID: cardId,
        };

        this.iparNetwork.getPostJson(SERVER_TYPE.adminIpar + 'RemoveCreditCard', data)
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    CommonUtils.showLoading();
                    bankCard = [];
                    this.getCreditCardInfo();
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'))
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log(error);
            })

    }

    /*收货地址Tv*/
    getBackCardTv(address) {
        let countryTv = [];
        for (i = 0; i < address.length; i++) {
            if (address[i] !== null && address[i] !== '') {
                countryTv.push(<Text
                    style={[StyleUtils.smallTvColor, StyleUtils.smallFont, styles.listTv]}>{address[i]}</Text>)
            }
        }
        return countryTv;
    }

    render() {
        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                />
                <AlertDialog
                    visible={this.state.showDialog}
                    requestClose={() => this.setState({showDialog: false})}
                    contentTv={I18n.t('default.deleteNote')}
                    leftBtnOnclick={() => {
                        this.deleteCardBtn(this.deleteRowData, this.deleteRowId);
                    }}

                />
                <ScrollView>
                    <View style={[StyleUtils.flex, {padding: 16}]}>
                        {ViewUtils.getTitleView(I18n.t('default.bankCard'), I18n.t('default.allDebitCard'))}
                        <View style={StyleUtils.lineStyle}/>

                        <ListView
                            renderRow={this.renderRow.bind(this)}
                            dataSource={this.state.dataSource}
                        />


                        {/*submitBtn*/}
                        {ViewUtils.getButton(I18n.t('default.addNewCard'), () => {
                            this.props.navigator.push({
                                component: AddBackCardPage, params: {
                                    callback: () => {
                                        bankCard = [];
                                        this.getCreditCardInfo();
                                        CommonUtils.showLoading();
                                    }
                                }
                            })//BankCardTypePage
                        }, {marginTop: 16, marginBottom: 16})}
                    </View>
                </ScrollView>

            </View>)
    }

    /*list render*/
    renderRow(rowData, sectionID, rowID) {


        return (<View>
            <Text
                style={[styles.cardTitle, StyleUtils.smallFont]}>{I18n.t('default.masterCard')} ({rowData.CardNumber.substr(-4)})</Text>
            {this.getBackCardTv([rowData.HolderName, rowData.BankdName ? rowData.BankdName : rowData.BrandName, rowData.CardNumber, rowData.ExpirationDate ? I18n.t('default.creditCard') : ''])}

            <View style={[StyleUtils.flex, StyleUtils.center, StyleUtils.rowDirection, styles.tabBox]}>
                <Text
                    onPress={() => {
                        this.setState({showDialog: true});
                        this.deleteRowData = rowData;
                        this.deleteRowId = rowID;

                        //this.deleteCardBtn(rowData, rowID)
                    }}
                    numberOfLines={1}
                    style={[styles.editTv, StyleUtils.smallFont]}>{I18n.t('default.delete')}</Text>
                <Text numberOfLines={1}
                      style={[styles.editTv, StyleUtils.smallFont]}>{I18n.t('default.setDefault')}</Text>
            </View>
            <View style={StyleUtils.lineStyle}/>
        </View>)
    }

    /*删除银行卡btn*/
    deleteCardBtn(rowData, rowId) {
        this.setState({showDialog: false});
        CommonUtils.showLoading();
        this.getDeleteCreditCard(rowData.CardID);
    }
}

const styles = StyleSheet.create({
    tabBox: {
        height: 35,
        marginTop: 10,
        marginRight: '30%',
    },
    listTv: {
        marginTop: 8,
        color: 'black',
        textAlign: 'left'

    },
    editTv: {
        color: 'black',
        fontSize: 16,
        flex: 1,
        textAlign: 'left'

    },
    cardTitle: {
        marginTop: 16,
        fontSize: 18,
        textAlign: 'left',

        color: 'black'
    }

});

